﻿using MassTransit;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Kingzad.MicroService.BusinessCore.Providers
{
    public interface IMassTransitProvider
    {
        Task PublishMessage(string message);
    }

    public class MassTransitProvider : IMassTransitProvider
    {
        private readonly IBusControl _busControl;
        private readonly ILogger<MassTransitProvider> _logger;

        public MassTransitProvider(ILogger<MassTransitProvider> logger, IBusControl busControl)
        {
            _logger = logger;
            _busControl = busControl;
        }

        public async Task PublishMessage(string message)
        {
            try
            {
                await _busControl.Publish<string>(message);
            }
            catch(Exception e)
            {
                _logger.LogError(e.Message + e.StackTrace);
            }
        }

        public async Task<string> RequestMessage(string message)
        {
            Task.WaitAll(_busControl.StartAsync());

            var client = _busControl.CreateRequestClient<string>(new Uri(_busControl.Address, "channelName"), TimeSpan.FromSeconds(5));

            try
            {
                var response = await client.GetResponse<string>(message);
                return response.Message;
            }
            catch(Exception e)
            {
                _logger.LogError(e.Message + e.StackTrace);
                return "no response back";
            }
        }

    }

    public class ResponseHandler : IConsumer<string>
    {
        public ResponseHandler()
        {
        }

        public async Task Consume(ConsumeContext<string> context)
        {
            await context.RespondAsync("response message");
        }
    }

    public class SubscribeHandler : IConsumer<string>
    {
        public SubscribeHandler()
        {
        }

        public async Task Consume(ConsumeContext<string> context)
        {
            var receviedMessage = context.Message;
            await Task.Run(() => { });
        }
    }
}
